#!/usr/bin/env bash
set -e
export -n CDPATH

if [ "$1" = "--debug" ]; then
  export NODENV_DEBUG=1
  shift
fi

if [ -n "$NODENV_DEBUG" ]; then
  export PS4='+ [${BASH_SOURCE##*/}:${LINENO}] '
  set -x
fi

READLINK=$(type -p greadlink readlink | head -1)
if [ -z "$READLINK" ]; then
  echo "nodenv: cannot find readlink - are you missing GNU coreutils?" >&2
  exit 1
fi

resolve_link() {
  $READLINK "$1"
}

abs_dirname() {
  local cwd="$(pwd)"
  local path="$1"

  while [ -n "$path" ]; do
    cd "${path%/*}"
    local name="${path##*/}"
    path="$(resolve_link "$name" || true)"
  done

  pwd
  cd "$cwd"
}

if [ -z "${NODENV_ROOT}" ]; then
  NODENV_ROOT="${HOME}/.nodenv"
else
  NODENV_ROOT="${NODENV_ROOT%/}"
fi
export NODENV_ROOT

if [ -z "${NODENV_DIR}" ]; then
  NODENV_DIR="$(pwd)"
else
  cd "$NODENV_DIR" 2>/dev/null || {
    echo "nodenv: cannot change working directory to \`$NODENV_DIR'"
    exit 1
  } >&2
  NODENV_DIR="$(pwd)"
  cd "$OLDPWD"
fi
export NODENV_DIR


shopt -s nullglob

bin_path="$(abs_dirname "$0")"
for plugin_bin in "${NODENV_ROOT}/plugins/"*/bin; do
  bin_path="${bin_path}:${plugin_bin}"
done
export PATH="${bin_path}:${PATH}"

hook_path="${NODENV_HOOK_PATH}:${NODENV_ROOT}/nodenv.d:/usr/local/etc/nodenv.d:/etc/nodenv.d:/usr/lib/nodenv/hooks"
for plugin_hook in "${NODENV_ROOT}/plugins/"*/etc/nodenv.d; do
  hook_path="${hook_path}:${plugin_hook}"
done
export NODENV_HOOK_PATH="$hook_path"

shopt -u nullglob


command="$1"
case "$command" in
"" | "-h" | "--help" )
  echo -e "$(nodenv---version)\n$(nodenv-help)" >&2
  ;;
"-v" )
  exec nodenv---version
  ;;
* )
  command_path="$(command -v "nodenv-$command" || true)"
  if [ -z "$command_path" ]; then
    echo "nodenv: no such command \`$command'" >&2
    exit 1
  fi

  shift 1
  exec "$command_path" "$@"
  ;;
esac
